package org.example.redis.impl;

import org.example.redis.Limiter;

import java.util.concurrent.atomic.AtomicInteger;

public class CountLimiter implements Limiter {
    private long currTime = System.currentTimeMillis();
    private final int maxCount = 10;
    // 假设1秒10个请求
    private final int period = 1;

    private static final AtomicInteger counter = new AtomicInteger(0);

    @Override
    public boolean tryAcquire(int count) {
        long time = System.currentTimeMillis();
        if (time - currTime < period * 1000) {
            // 1秒之内
            int tokens = counter.get();
            if (tokens >= maxCount) {
                return false;
            }
            counter.incrementAndGet();
            return true;
        } else {
            currTime = System.currentTimeMillis();
            // 清0
            counter.set(0);
            return false;
        }
    }
}
